<template>
  <div id="articleID">
    <div class="title">{{articleData.title}}</div>
    <div class="title-info">
      <span class="author">作者：{{articleData.author.name}}</span>
      <span class="time">发表时间：{{conversionDate(articleData.date)}}</span>
      <span class="view">浏览量：{{articleData.vistor}}</span>
    </div>
    <!-- 文章内容 -->
    <article>
      <main id="mdToHTML"></main>
    </article>
    <div class="hr"></div>
    <!-- 其他详情 -->
    <div class="info">
      <!-- 上下文章 -->
      <div class="article">
        <p><span class="tit" v-if="prevTitle">上一篇</span> <a :href="/article/+prevHref+'?type=share'" target="_balnk">{{prevTitle}}</a></p>
        <p><span class="tit" v-if="nextTitle">下一篇</span> <a :href="/article/+nextHref+'?type=share'" target="_balnk">{{nextTitle}}</a></p>
      </div> 
      <!-- 分享 -->
      <div class="share">
        <!-- 二维码 -->
        <div class="qrcode">
          <div id="qrcode"></div>
          <span class="tit">扫码分享文章内容</span>
        </div>  
        <!-- 分享链接 -->
        <div class="link">
          <p>分享到:</p>
          <div class="shareIcon">
            <img src="../assets/img/qq.jpg" alt="" @click="shareQQ">
            <img src="../assets/img/xlwb.jpg" alt="" @click="shareXl">
          </div>
        </div>
      </div> 
    </div>
    <!-- 用户点赞收藏 -->
    <div class="collection">
      <el-affix position="bottom" :offset="0">
        <div class="center">
          <div class="articleAuthor">
            <img :src="baseURL+articleData.author.phone" alt="">
            <span>{{articleData.author.name}}</span>
          </div>
          <div class="articleInfo">
            <div class="info">
              <i class="iconfont icon-dianzan_active" 
              :class="{
                active: userInfo.name && likes.includes(userInfo._id)
              }"
              @click="userThumbs"></i>
              <span>{{likes.length}}</span>
            </div>
            <div class="info">
              <i class="iconfont icon-shoucang" 
              :class="{
                collections:userInfo.name && collection.includes(userInfo._id)
              }"
              @click="userCollection"></i>
              <span>{{collection.length}}</span>
            </div>
            <div class="info">
              <i class="iconfont icon-pl" @click="userComment"></i>
            </div>
          </div>
        </div>
      </el-affix>
    </div>
    <!-- 文章评论 -->
    <div class="comment" id="comment">
      <!-- 用户提交 -->
      <div class="submit">
        <el-form 
        ref="submitForm" 
        :model="submitForm"
        :rules="rules" 
        :inline="true">
            <el-input
            type="textarea" 
            :rows="3" 
            placeholder="请输入评论的内容" 
            v-model.trim="submitForm.textarea"
            maxlength='150'
            show-word-limit
            prop="textarea"
            ></el-input>
          <el-form-item label="验证码" prop="code">
            <el-input  width="80px" v-model.trim="submitForm.code"></el-input>
          </el-form-item>
          <img id="code" title="看不清?换一张" :src="code+'?id='+stamp"  alt="" @click="replaceCode">
          <el-button type="primary" id="btn" round @click="submit">发表评论</el-button>
        </el-form>
      </div>
      <!-- 评论展示 -->
      <div class="show">
        <div class="title">全部评论 ({{commontList.length}} 条)</div>
        <div class="text">
          <div class="list" v-if="commontList.length"
            v-for="item in commontList"
          >
            <span class="author">{{item.name}} </span> &nbsp;:
            <span class="center">{{item.text}}</span>
            <span class="time">{{conversionDate(item.date)}}</span>
          </div>
          <el-empty v-else description="暂时没有评论哦，快来抢沙发吧~"></el-empty>
        </div>
      </div>
    </div>
    <!-- 回到顶部 -->
    <el-backtop></el-backtop>
  </div>
</template>
 
<script>
import QRCode from "qrcodejs2"
import $ from 'jquery';
import {mapState} from "vuex"
export default {
  name: '',
  data(){
    return{
      // 文章内容
      articleData:{
        // 文章id
        _id:"",
        // 文章的标题
        title:"", 
        // 作者 
        author:"",   
        // 浏览量 
        vistor:0,
        // md所在位置
        md:"",
        // 作者头像
        phone:""
      },
      // 点赞数
      likes:[],
      // 收藏数
      collection:[],
      // 上一篇文章标题             
      prevTitle:"",  
        // 上一篇文章的id  
      prevHref:"", 
      // 下一篇文章标题  
      nextTitle:"",   
      // 下一篇文章的id    
      nextHref:"",      
      // 二维码内容
      shareLink:window.location.href, 
      // 验证码
      code:"https://fkshfw30.jz.fkw.com/validateCode.jsp",
      // 当前时间戳
      stamp:Date.now(),
      // 提交表单
      submitForm:{
        code:"",
        // 留言内容
        textarea:""
      },
      // 表单验证
      rules:{
        name:[
          { required: true, trigger: 'blur' },
          { min: 3, max: 6, message: '名字长度在 3 到 6 个字符', trigger: 'change' }
        ],
        code:[
          { required: true, trigger: 'blur' },
          {
            validator(rule,value,cb){
              if(value.length!==4){
                cb(new Error("验证码不正确"))
              }
              cb()
            }
          }
        ],
        textarea:[
          { required: true, trigger: 'blur' },
        ]
      },
      // 评论列表
      commontList:[]

    }
  },
  methods:{
    // 生成页面二维码
    qrcode(){ 
    new QRCode('qrcode', { 
      width: 70,
      height: 70,        // 高度
      text:  this.shareLink,   // 二维码内容
      background: '#fff',   // 背景色
      foreground: '#ff0'    // 前景色
      })
    },
    // 跳转到QQ空间
    shareQQ(){
      window.open(`http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=${(this.shareLink)}&pics=${(this.baseURL+this.articleData.cover[0])}&title=${this.articleData.title}&summary=${(this.articleData.des)}`)
    },
    // 跳转到新浪
    shareXl(){
      window.open(`http://service.weibo.com/share/share.php?appkey=583395093&title=${this.shareTitle}&url=${(this.shareLink)}&source=bshare&retcode=0&ralateUid=`)
    },
    // 更换验证码
    replaceCode(){
      this.stamp = Date.now()
    },
    // 发表评论
    submit(){
      this.$refs.submitForm.validate(async v=>{
        if(!this.submitForm.textarea.trim()) {
          return this.$message.warning("评论内容不能为空哦~")
        }
        if(!v) return false
        this.$message.success("发表成功")
      })
    },
     // 日期转化
    conversionDate(date){
      let time = new Date(date)
      let year = time.getFullYear()
      let month = time.getMonth()+1<10?"0"+( time.getMonth()+1): time.getMonth()+1
      let day = time.getDate()<10?"0"+time.getDate():time.getDate()
      let h = time.getHours()<10?"0"+time.getHours():time.getHours()
      let f = time.getMinutes()<10?"0"+time.getMinutes():time.getMinutes()
      let s = time.getSeconds()<10?"0"+time.getSeconds():time.getSeconds()
      return `${year}-${month}-${day} ${h}:${f}:${s}`
    },
    // 请求文章详情
    async getArticleIDInfo(){
      // 获取请求类型
      let type = this.$route.query.type
      // 获取文章的id
      let _id = this.$route.params.id
        // 请求分享文章
        let {data} = await this.$axios.get("/client/share/getArticle",{
          params:{
            _id,type
          }
        })
        if(data.code){
          this.$message.warning(data.mes)
          this.$router.replace("/123")
          return
        }
        // 文章详情信息
        this.articleData = data.data
        // 点赞
        this.likes = data.data.likes
        // 收藏
        this.collection = data.data.collections
        // 评论列表
        this.commontList = data.data.comment
        // 上一篇文章信息
        if(!data.prev){
          this.prevTitle = null
          this.prevHref = null
        }else{
          this.prevTitle = data.prev.title
          this.prevHref = data.prev._id
        }
        // 下一篇文章信息
        if(!data.next){
          this.nextTitle = null
          this.nextHref = null
        }else{
          this.nextTitle = data.next.title
          this.nextHref = data.next._id
        }
        // 加载md
        let res = await this.$axios.get(`${this.articleData.md}`) // md所在位置
        editormd.markdownToHTML("mdToHTML", {
          markdown: res.data,
          emoji: true
        })
         // 用户浏览历史记录
        this.userRecord()
    },
    // 提交评论
    submit(){
      this.$refs.submitForm.validate(async v=>{
        if(!v) return false
        // 获取请求类型
        let type = this.$route.query.type
        let {data} = await this.$axios.post("/client/share/commont",{
          text:this.submitForm.textarea,
          _id:this.articleData._id,
          type
        })
        if(data.code) return this.$message.warning(data.mes)
        this.$message.success(data.mes)
        // 清空表单
        this.$refs.submitForm.resetFields()
        this.submitForm.textarea = ""
        // 更新数据
        this.lazyRefresh()
      })
    },
    // 用户点赞
    async userThumbs(){
      // 获取请求类型
      let type = this.$route.query.type
      let {data} = await this.$axios.post("/client/userOperation/thumbs",{
        aID:this.articleData._id,
        type
      })
      if(data.code) return this.$message.warning(data.mes)
      // 更新数据
      this.lazyRefresh()
    },
    // 用户点赞收藏刷新 评论
    async lazyRefresh(){
       // 获取请求类型
      let type = this.$route.query.type
      // 获取文章的id
      let _id = this.$route.params.id
      let {data} = await this.$axios.get("/client/share/getArticle",{
        params:{
          _id,type
        }
      })
      if(data.code) return this.$message.warning(data.mes)
      // 点赞数据
      this.likes = data.data.likes
      // 收藏数据
      this.collection = data.data.collections
      // 评论数据
      this.commontList = data.data.comment
    },
    // 用户收藏
    async userCollection(){
      // 获取请求类型
      let type = this.$route.query.type
      // 获取文章的id
      let _id = this.$route.params.id
      let {data} = await this.$axios.post("/client/userOperation/collection",{
        aID:this.articleData._id,
        type
      })
      if(data.code) return this.$message.warning(data.mes)
      this.$message.success(data.mes)
      // 更新数据
      this.lazyRefresh()
    },
    // 跳转到评论
    userComment(){
      $("html,body").animate({
        scrollTop:$("#comment").offset().top - 100
      },600)
    },
    // 用户浏览记录
    async userRecord(){
       // 获取请求类型
      let type = this.$route.query.type
      // 获取文章的id
      let _id = this.$route.params.id
      let {data} = await this.$axios.post("/client/userOperation/record",{
        aID:this.articleData._id,
        type
      })
       if(data.code) return 
    }
  },
  async created(){
    // 请求文章详情
    this.getArticleIDInfo()
  },
  mounted(){
    // 加载二维码
    this.$nextTick (function () {
      this.qrcode();
    }) 

  },
  computed:{
    ...mapState(["userInfo"])
  },
}
</script>

<style scoped lang='less'>
#articleID{
  width: 1200px;
  margin: 0 auto;
  padding: 10px 0;
  .title{
    font-size: 25px;
    color: #333;

  }
  .title-info{
    margin: 30px 0;
    font-size: 13px;
    color: #929292;
    span{
      margin-right: 22px;
    }
  }
  article{
    margin-top: -20px;
    margin-left: -10px;
  }
  .hr{
    width: 100%;
    height: 1px;
    background-color: #ebebeb;
    margin: 10px 0;
  }
  .info{
    width: 100%;
    height: 100px;
    display: flex;
    margin-top:20px;
    justify-content: space-between;
    .article{
      width: 300px;
      height: 100px;
      color: #666666;
      font-size: 14px;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      p{
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .tit{
        margin-right: 20px;
      }
      a{
        text-decoration: none;
        color: #666;
        &:hover{
          text-decoration: underline;
          color: #FEC60B;
        }
      }
    }
    .share{
      width: 320px;
      height: 100px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .qrcode{
        width: 100px;
        height: 100px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-around;
        .tit{
          font-size: 12px;
          color: #666;
        } 
      }
      .link{
        width: 200px;
        height: 50px;
        font-size: 13px;
        color: #666;
        line-height: 50px;
        display: flex;
        align-items: center;
        .shareIcon{
          display: flex;    
          img{
            width: 40px;
            height: 40px;
            border-radius: 50%;
            cursor: pointer;
            margin-left: 10px;
            &:hover{
              box-shadow: 0px 0px 10px #929292;
            }
          }
        }
      }
    }
  }
  .comment{
    width: 100%;
    margin-top: 20px;
    background-color: #FAFAFA;
    .submit{
      margin-top: 20px;
      position: relative;
      .el-form{
        .el-textarea{
          margin-bottom: 20px;
        }
      }
     #code{
      //  display:
      width: 100px;
      height: 35px;
      display: inline-box;
      position: absolute;
      margin-top: 3px;
      cursor: pointer;
      margin-left: 10px;
     }
     #btn{
       position: absolute;
       right: 20px;
     }
    }
    .show{
      margin: 10px 0;
      width: 1170px;
      margin: 20px auto;
      padding-bottom: 10px;
      .title{
        font-size: 14px;
        color:#666;
        width: 100%;
        height: 40px;
        box-sizing: border-box;
        border-bottom: 1px solid rgb(219, 217, 217);
      }
      .text{
        margin-top: 30px;
        .list{
          line-height: 25px;
          margin-bottom: 20px;
          box-sizing: border-box;
          border-bottom: 1px solid #ebe9e9;
          padding-bottom: 10px;
          &:last-child{
             border-bottom: 1px solid transparent;
          }
          .author{
            font-size: 16px;
            background-color: rgb(226, 224, 224);
            color: red;
            padding: 3px 10px;
            user-select: none;
          }
          .center{
            color: #666;
          }
          .time{
            font-size: 14px;
            color: purple;
            margin-left: 15px;
            background-color: rgba(211, 208, 208,.4);
            user-select: none;
          }
        }
      }
    }
  }
  .collection{
    width: 100%;
    height: 70px;
    background-color: #fff;
    margin-top:10px;
    user-select: none;
    .center{
      width: 1220px;
      height: 70px;
      display: flex;
      justify-content: space-between;
      padding: 10px 0 10px;
      background-color: #fff;
      border-top: 1px solid #f1eeee;
      align-items: center;
      .articleAuthor{
        display: flex;
        width: 150px;
        justify-content: space-around;
        align-items: center;
        img{
          border-radius: 50%;
        }
        span{
          font-weight: bold;
          font-size: 16px;
        }
      }
      .articleInfo{
        display: flex;
        flex-direction: row;
        width: 150px;
        height: 100px;
        margin-right:20px;
        justify-content: space-between;
        align-items: center;
        .info{
          margin: 0;
          width: 25px;
          display: flex;
          height: 90px;
          align-items: center;
          justify-content: space-evenly;
          i{
            font-size: 20px;
            color: rgb(97, 95, 95);
            cursor: pointer;
            margin-right: 5px;
            &.active{
              color: red;
            }
            &.collections{
              color: yellow;
            }
          }
        }
      }
      img{
        width: 50px;
        height: 50px;
      }
    }
  }
}
</style>